import { Ionicons } from "@expo/vector-icons";
import { Image } from "expo-image";
import { LinearGradient } from "expo-linear-gradient";
import { useRouter } from "expo-router";
import React, { useState } from "react";
import {
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { FreePuzzleIcon } from "../../components/icons/FreePuzzleIcon";
import { PhotoEditIcon } from "../../components/icons/PhotoEditIcon";
import { QuickPuzzleIcon } from "../../components/icons/QuickPuzzleIcon";
import { TemplateIcon } from "../../components/icons/TemplateIcon";

// 模板集合组件
interface TemplateCollectionProps {
  title: string;
  emoji: string;
  categories: string[];
  templates: { [key: string]: { id: number; image: string; title: string }[] };
}

const TemplateCollection: React.FC<TemplateCollectionProps> = ({
  categories,
  templates,
}) => {
  const [activeCategory, setActiveCategory] = useState(categories[0] || "All");

  // 瀑布流渲染函数
  const renderWaterfallLayout = () => {
    const data = templates[activeCategory] || [];
    const leftColumn: any[] = [];
    const rightColumn: any[] = [];

    // 模拟不同高度的卡片
    data.forEach((item, index) => {
      const randomHeight = 150 + Math.random() * 100; // 随机高度150-250
      const cardWithHeight = { ...item, height: randomHeight };

      if (index % 2 === 0) {
        leftColumn.push(cardWithHeight);
      } else {
        rightColumn.push(cardWithHeight);
      }
    });

    return (
      <View style={styles.waterfallContainer}>
        <View style={styles.waterfallColumn}>
          {leftColumn.map((item) => (
            <TouchableOpacity
              key={`left-${item.id}`}
              style={styles.waterfallCard}
            >
              <Image
                source={{ uri: item.image }}
                style={[styles.waterfallImage, { height: item.height }]}
              />
              {/* <Text style={styles.waterfallTitle}>{item.title}</Text> */}
            </TouchableOpacity>
          ))}
        </View>
        <View style={styles.waterfallColumn}>
          {rightColumn.map((item) => (
            <TouchableOpacity
              key={`right-${item.id}`}
              style={styles.waterfallCardRight}
            >
              <Image
                source={{ uri: item.image }}
                style={[styles.waterfallImage, { height: item.height }]}
              />
              {/* <Text style={styles.waterfallTitle}>{item.title}</Text> */}
            </TouchableOpacity>
          ))}
        </View>
      </View>
    );
  };

  return (
    <View style={styles.templateSection}>
      {/* 分类标签 */}
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        style={styles.categoryScrollView}
      >
        {categories.map((category, index) => (
          <TouchableOpacity
            key={index}
            style={[
              styles.categoryButton,
              activeCategory === category && styles.activeCategoryButton,
            ]}
            onPress={() => setActiveCategory(category)}
          >
            <Text
              style={[
                styles.categoryText,
                activeCategory === category && styles.activeCategoryText,
              ]}
            >
              {category}
            </Text>
          </TouchableOpacity>
        ))}
      </ScrollView>

      {/* 瀑布流模板展示 */}
      <ScrollView showsVerticalScrollIndicator={false}>
        {renderWaterfallLayout()}
      </ScrollView>
    </View>
  );
};

export default function TabTwoScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();

  // 轮播图数据
  const bannerData = [
    {
      id: 1,
      image:
        "https://images.unsplash.com/photo-1513475382585-d06e58bcb0e0?w=400&h=200&fit=crop",
      title: "剪映支持作图啦",
      subtitle: "NEW",
      badge: "B&J",
    },
  ];

  // 功能图标数据
  const functionIcons = [
    { id: 1, name: "智能抠图", Icon: QuickPuzzleIcon, color: "#333" },
    { id: 2, name: "长拼图", Icon: FreePuzzleIcon, color: "#333" },
    { id: 3, name: "图片分割", Icon: TemplateIcon, color: "#333" },
    { id: 4, name: "照片编辑", Icon: PhotoEditIcon, color: "#333" },
  ];

  // 模板数据
  const templateData = {
    精选: [
      {
        id: 1,
        image:
          "https://images.unsplash.com/photo-1513475382585-d06e58bcb0e0?w=300&h=200&fit=crop",
        title: "精选模板1",
      },
      {
        id: 2,
        image:
          "https://images.unsplash.com/photo-1464207687429-7505649dae38?w=300&h=200&fit=crop",
        title: "精选模板2",
      },
      {
        id: 3,
        image:
          "https://images.unsplash.com/photo-1530103862676-de8c9debad1d?w=300&h=200&fit=crop",
        title: "精选模板3",
      },
      {
        id: 4,
        image:
          "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=300&h=200&fit=crop",
        title: "精选模板4",
      },
    ],
    文字语录: [
      {
        id: 5,
        image:
          "https://images.unsplash.com/photo-1455390582262-044cdead277a?w=300&h=200&fit=crop",
        title: "励志语录",
      },
      {
        id: 6,
        image:
          "https://images.unsplash.com/photo-1481627834876-b7833e8f5570?w=300&h=200&fit=crop",
        title: "心情文字",
      },
      {
        id: 7,
        image:
          "https://images.unsplash.com/photo-1434030216411-0b793f4b4173?w=300&h=200&fit=crop",
        title: "名言警句",
      },
    ],
    封面: [
      {
        id: 8,
        image:
          "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300&h=200&fit=crop",
        title: "杂志封面",
      },
      {
        id: 9,
        image:
          "https://images.unsplash.com/photo-1586953208448-b95a79798f07?w=300&h=200&fit=crop",
        title: "书籍封面",
      },
      {
        id: 10,
        image:
          "https://images.unsplash.com/photo-1542831371-29b0f74f9713?w=300&h=200&fit=crop",
        title: "专辑封面",
      },
    ],
    营销: [
      {
        id: 11,
        image:
          "https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=300&h=200&fit=crop",
        title: "促销海报",
      },
      {
        id: 12,
        image:
          "https://images.unsplash.com/photo-1553729459-efe14ef6055d?w=300&h=200&fit=crop",
        title: "广告设计",
      },
    ],
    拼图: [
      {
        id: 13,
        image:
          "https://images.unsplash.com/photo-1606092195730-5d7b9af1efc5?w=300&h=200&fit=crop",
        title: "照片拼图",
      },
      {
        id: 14,
        image:
          "https://images.unsplash.com/photo-1515378791036-0648a814c963?w=300&h=200&fit=crop",
        title: "创意拼图",
      },
    ],
    趣味: [
      {
        id: 15,
        image:
          "https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=300&h=200&fit=crop",
        title: "趣味贴纸",
      },
      {
        id: 16,
        image:
          "https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=300&h=200&fit=crop",
        title: "卡通头像",
      },
    ],
  };

  return (
    <View style={styles.container}>
      {/* 顶部渐变背景 */}
      <LinearGradient
        colors={["#FFB6C1", "#F8F9FA"]}
        style={[styles.headerGradient, { paddingTop: insets.top }]}
      >
        {/* 搜索栏 */}
        <View style={styles.searchContainer}>
          <TouchableOpacity style={styles.searchButton}>
            <Ionicons name="search" size={20} color="#666" />
            <Text style={styles.searchText}>去搜模板</Text>
          </TouchableOpacity>
        </View>

        {/* 轮播图 */}
        <View style={styles.bannerContainer}>
          <Image
            source={{ uri: bannerData[0].image }}
            style={styles.bannerImage}
          />
          <View style={styles.bannerContent}>
            <View style={styles.bannerTextContainer}>
              <Text style={styles.bannerSubtitle}>
                {bannerData[0].subtitle}
              </Text>
              <Text style={styles.bannerTitle}>{bannerData[0].title}</Text>
            </View>
            <View style={styles.bannerBadge}>
              <Text style={styles.bannerBadgeText}>{bannerData[0].badge}</Text>
            </View>
          </View>
        </View>

        {/* 智能设计和图片编辑按钮 */}
        <View style={styles.topButtonsContainer}>
          <TouchableOpacity
            style={styles.topButton}
            onPress={() => {
              router.push("/detail/quick-puzzle?mode=edit");
            }}
          >
            <View style={styles.topButtonIcon}>
              <Ionicons name="bulb" size={20} color="#8B4513" />
            </View>
            <Text style={styles.topButtonText}>快速拼图</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.topButton}
            onPress={() => {
              router.push("/detail/free-puzzle");
            }}
          >
            <View style={styles.topButtonIcon}>
              <Ionicons name="image" size={20} color="#228B22" />
            </View>
            <Text style={styles.topButtonText}>自由拼图</Text>
          </TouchableOpacity>
        </View>
      </LinearGradient>

      <ScrollView
        style={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        {/* 功能图标区 */}
        <View style={styles.functionContainer}>
          {functionIcons.map((item) => (
            <TouchableOpacity
              key={item.id}
              style={styles.functionItem}
              onPress={() => {
                if (item.name === "照片编辑") {
                  router.push({
                    pathname: "/detail/select-image",
                    params: {
                      mode: "single",
                      mediaType: "photo",
                      maxCount: 1,
                    },
                  });
                } else if (item.name === "自由拼图") {
                  router.push("/detail/select-image?mode=puzzle");
                }
              }}
            >
              <Ionicons
                name={
                  item.name === "快速拼图"
                    ? "grid"
                    : item.name === "自由拼图"
                    ? "apps"
                    : item.name === "主题模板"
                    ? "document-text"
                    : item.name === "照片编辑"
                    ? "image"
                    : "help"
                }
                size={32}
                color={item.color}
              />
              <Text style={styles.functionText}>{item.name}</Text>
            </TouchableOpacity>
          ))}
        </View>

        {/* 模板集合 */}
        <TemplateCollection
          title="模板集合"
          emoji=""
          categories={["精选", "文字语录", "封面", "营销", "拼图", "趣味"]}
          templates={templateData}
        />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#F8F9FA",
  },
  headerGradient: {
    paddingHorizontal: 20,
  },
  searchContainer: {
    marginBottom: 15,
  },
  searchButton: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "rgba(255,255,255,0.9)",
    paddingHorizontal: 15,
    paddingVertical: 10,
    borderRadius: 20,
    alignSelf: "flex-end",
    minWidth: 100,
  },
  searchText: {
    marginLeft: 5,
    fontSize: 14,
    color: "#666",
  },
  bannerContainer: {
    position: "relative",
    marginBottom: 15,
  },
  bannerImage: {
    width: "100%",
    height: 120,
    borderRadius: 12,
  },
  bannerContent: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    padding: 15,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-start",
  },
  bannerTextContainer: {
    flex: 1,
  },
  bannerSubtitle: {
    fontSize: 12,
    color: "#FF6B35",
    fontWeight: "bold",
    marginBottom: 5,
  },
  bannerTitle: {
    fontSize: 18,
    color: "white",
    fontWeight: "bold",
  },
  bannerBadge: {
    backgroundColor: "#FFD700",
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 8,
  },
  bannerBadgeText: {
    fontSize: 12,
    fontWeight: "bold",
    color: "#333",
  },
  topButtonsContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
  topButton: {
    flex: 1,
    backgroundColor: "rgba(255,255,255,0.9)",
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 20,
    paddingHorizontal: 15,
    borderRadius: 4,
  },
  topButtonIcon: {
    width: 30,
    height: 30,
    borderRadius: 15,
    backgroundColor: "#F0F0F0",
    justifyContent: "center",
    alignItems: "center",
    marginRight: 8,
  },
  topButtonText: {
    fontSize: 14,
    color: "#333",
    fontWeight: "500",
  },
  scrollContent: {
    flex: 1,
  },
  functionContainer: {
    flexDirection: "row",
    justifyContent: "space-around",
    paddingHorizontal: 20,
    paddingVertical: 20,
  },
  functionItem: {
    alignItems: "center",
  },
  functionText: {
    fontSize: 12,
    color: "#333",
    textAlign: "center",
    marginTop: 8,
  },
  categoryScrollContainer: {
    marginBottom: 15,
  },
  categoryRow: {
    flexDirection: "row",
    paddingHorizontal: 20,
  },
  categoryTag: {
    backgroundColor: "#F0F0F0",
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 15,
    marginRight: 10,
  },
  categoryTagText: {
    fontSize: 12,
    color: "#666",
  },
  selectButton: {
    backgroundColor: "#4ECDC4",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    marginHorizontal: 20,
    paddingVertical: 15,
    borderRadius: 25,
    marginBottom: 15,
  },
  selectButtonText: {
    color: "white",
    fontSize: 16,
    fontWeight: "600",
    marginLeft: 8,
  },
  selectedImagesContainer: {
    marginHorizontal: 20,
    marginBottom: 20,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: "600",
    color: "#333",
    marginBottom: 15,
  },
  selectedImageWrapper: {
    position: "relative",
    marginRight: 10,
  },
  selectedImage: {
    width: 80,
    height: 80,
    borderRadius: 8,
  },
  removeButton: {
    position: "absolute",
    top: -5,
    right: -5,
    backgroundColor: "white",
    borderRadius: 10,
  },
  templateSection: {
    backgroundColor: "white",
    paddingHorizontal: 20,
    paddingVertical: 20,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    marginTop: 0,
  },
  templateTitle: {
    fontSize: 18,
    fontWeight: "600",
    color: "#333",
    flex: 1,
    marginLeft: 10,
  },
  categoryScrollView: {
    marginBottom: 20,
  },
  categoryContainer: {
    flexDirection: "row",
    marginBottom: 20,
  },
  categoryButton: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    marginRight: 10,
    borderRadius: 20,
  },
  activeCategoryButton: {
    backgroundColor: "#FDEEF1",
  },
  categoryText: {
    fontSize: 14,
    color: "#0A1310",
  },
  activeCategoryText: {
    color: "red",
  },
  waterfallContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
  waterfallColumn: {
    flex: 1,
  },
  waterfallCard: {
    backgroundColor: "white",
    marginBottom: 10,
    marginRight: 5,
  },
  waterfallCardRight: {
    backgroundColor: "white",
    marginBottom: 10,
    marginLeft: 5,
  },
  waterfallImage: {
    width: "100%",
    borderRadius: 12,
  },
  waterfallTitle: {
    fontSize: 12,
    color: "#333",
    textAlign: "center",
    padding: 10,
  },
  templateCard: {
    width: 120,
    marginRight: 15,
  },
  templateImage: {
    width: 120,
    height: 160,
    borderRadius: 12,
    marginBottom: 8,
  },
  templateCardTitle: {
    fontSize: 12,
    color: "#333",
    textAlign: "center",
  },
});
